<template>
  <div>
    <a-modal
      title="水印设置"
      :width="800"
      :visible="visible"
      :bodyStyle="{ background: '#eee', padding: '10px',zIndex: 999 }"
      @cancel="handleWaterCancel"
      @ok="handleWaterOk"
      destroyOnClose
      cancelText="关闭"
    >
      <div class="watermark">
        <div class="wleft">
          <div style="color: #333">文字水印</div>
          <div class="wcontent">
            <div class="title"><span>内</span><span>容(I)：</span></div>
            <a-input style="width: 80%" v-model.trim="printInfo.content" @change="handleChange" placeholder="请输入水印内容"></a-input>
          </div>
          <div class="wcontent">
            <div class="title"><span>字</span><span>号(S)：</span></div>
            <a-input-number style="width: 120px" v-model="printInfo.font" @change="handleChange" :precision="0" :min="12" :max="100"></a-input-number>
          </div>
          <!-- <div class="wcontent">
            <div class="title"><span>字</span><span>体(E)：</span></div>
            <a-input style="width: 80%;" disabled v-model="printInfo.size"></a-input>
          </div>
          <div class="wcontent">
            <div class="title"><span>字</span><span>号(S)：</span></div>
            <a-select v-model="printInfo.font" style="width: 120px">
              <a-select-option value="auto">自动</a-select-option>
            </a-select>
          </div>
          <div class="wcontent">
            <div class="title"><span>颜</span><span>色(C)：</span></div>
            <a-input style="width: 120px" type="color" v-model="printInfo.color"></a-input>
          </div>
          <div class="wcontent">
            <div class="title"><span>版</span><span>式(O)：</span></div>
            <a-select v-model="printInfo.type" style="width: 120px">
              <a-select-option value="level">水平</a-select-option>
              <a-select-option value="incline">倾斜</a-select-option>
            </a-select>
          </div>
          <div class="wcontent">
            <div class="title"><span>透</span><span>明</span><span>度(R)：</span></div>
            <a-input style="width: 120px" type="range" v-model="printInfo.transparency"></a-input>
            <a-input-number id="inputNumber" style="width: 80px;margin: 0 8px" v-model="printInfo.transparency" :min="0" :max="100" />%
          </div> -->
        </div>
        <div class="wright">
          <iframe :src="viewSrc" frameborder="0" :title="wValue" width="220" height="280"></iframe>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib'
import { axios } from '@/utils/request'

export default {
  data() {
    return {
      printInfo: {
        // size: '微软雅黑',
        content: '',
        font: 50,
        // color: '',
        // type: 'incline', // level
        // transparency: 50
      },
      visible: false,
      viewSrc: '',
      downSrc: '',
      downloadSrc: '',
      wValue: '',
    }
  },
  methods: {
    getPreview(text) {
      const _self = this
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + this.wValue
      axios({
        url: url,
        params: {},
        method: 'get',
        responseType: 'blob',
      }).then((res) => {
        res
          .arrayBuffer()
          .then(async (buffer) => {
            const existingPdfBytes = buffer
            const pdfDoc = await PDFDocument.load(existingPdfBytes)
            _self.addCanvasWatermark(pdfDoc, text)
            // _self.downloadCanvasWatermark(pdfDoc, text)
          })
          .catch((e) => console.error('[Preview Pdf Error]:', e))
      })
    },
    handleChange(e) {
      if (this.printInfo.content) {
        this.getPreview(this.printInfo.content)
      } else {
        this.downSrc = ''
        this.viewSrc = ''
        this.downloadSrc = ''
      }
    },
    addCanvasWatermark(pdfDoc, text) {
      const _self = this
      const pages = pdfDoc.getPages()
      const size = pages[0].getSize()
      let pageWidth = size.width
      let pageHeight = size.height
      let canvas = document.createElement('canvas')
      let canvasWidth = (canvas.width = pageWidth)
      let canvasHeight = (canvas.height = pageHeight)
      let fontSize = 50
      if(_self.printInfo.font>=100){
        fontSize = 100
      } else if (_self.printInfo.font<=12) {
        fontSize = 12
      } else {
        fontSize = _self.printInfo.font
      }
      const context = canvas.getContext('2d')
      // 先平移到画布中心
      context.translate(pageWidth / 2, pageHeight / 2) // 在绕画布逆方向旋转30度
      context.rotate(-Math.PI / 6) // 在还原画布的坐标中心
      context.translate(-pageWidth / 2, -pageHeight / 2)
      context.font = fontSize+'px Arial'
      context.textAlign = 'center'
      context.textBaseline = 'middle'
      context.fillStyle = 'rgba(187, 187, 187, .4)' // 字体颜色
      context.fillText(text, canvasWidth / 2, canvasHeight / 2)
      context.restore() // 恢复之前保存的状态 // 图片的base64编码路径
      let dataUrl = canvas.toDataURL('image/png') // 使用Xhr请求获取图片Blob
      let xhr = new XMLHttpRequest()
      xhr.open('get', dataUrl, true)
      xhr.responseType = 'blob'
      xhr.onload = (res) => {
        const imgBlob = res.target.response // 获取Blob图片Buffer
        imgBlob.arrayBuffer().then(async (buffer) => {
          const pngImage = await pdfDoc.embedPng(buffer)
          for (let i = 0; i < pages.length; i++) {
            pages[i].drawImage(pngImage)
          } // 序列化为字节
          const pdfBytes = await pdfDoc.save()
          const URL = window.URL || window.webkitURL
          const href = URL.createObjectURL(new Blob([pdfBytes], { type: 'application/pdf;charset=utf-8' }))
          _self.viewSrc = href+'#toolbar=0&navpanes=0'
          _self.downSrc = href
        })
      }
      xhr.send()
    },
    downloadCanvasWatermark(pdfDoc, text) {
      const _self = this
      const pages = pdfDoc.getPages()
      const size = pages[0].getSize()
      let pageWidth = size.width
      let pageHeight = size.height
      let fontSize = ''
      if (pageWidth > 0 && pageWidth < 800) {
        fontSize = '30px Arial'
      } else if (pageWidth > 800) {
        fontSize = '50px Arial'
      }
      let canvas = document.createElement('canvas')
      let canvasWidth = (canvas.width = pageWidth)
      let canvasHeight = (canvas.height = pageHeight)
      const context = canvas.getContext('2d')
      // 先平移到画布中心
      context.translate(pageWidth / 2, pageHeight / 2) // 在绕画布逆方向旋转30度
      context.rotate(-Math.PI / 6) // 在还原画布的坐标中心
      context.translate(-pageWidth / 2, -pageHeight / 2)
      context.font = fontSize
      context.textAlign = 'center'
      context.textBaseline = 'middle'
      context.fillStyle = 'rgba(187, 187, 187, .4)' // 字体颜色
      context.fillText(text, canvasWidth / 2, canvasHeight / 2)
      context.restore() // 恢复之前保存的状态 // 图片的base64编码路径
      let dataUrl = canvas.toDataURL('image/png') // 使用Xhr请求获取图片Blob
      let xhr = new XMLHttpRequest()
      xhr.open('get', dataUrl, true)
      xhr.responseType = 'blob'
      xhr.onload = (res) => {
        const imgBlob = res.target.response // 获取Blob图片Buffer
        imgBlob.arrayBuffer().then(async (buffer) => {
          const pngImage = await pdfDoc.embedPng(buffer)
          for (let i = 0; i < pages.length; i++) {
            pages[i].drawImage(pngImage)
          } // 序列化为字节
          const pdfBytes = await pdfDoc.save()
          const URL = window.URL || window.webkitURL
          const href = URL.createObjectURL(new Blob([pdfBytes], { type: 'application/pdf;charset=utf-8' }))
          _self.downloadSrc = href
        })
      }
      xhr.send()
    },
    handleWaterCancel() {
      this.visible = false
      this.wValue = ''
      this.viewSrc = ''
      this.downSrc = ''
      this.downloadSrc = ''
      this.printInfo.content = ''
      this.printInfo.font = 50
    },
    handleWaterOk() {
      if (!this.printInfo.content) {
        this.$message.warn('请输入水印内容!')
        return
      }
      // this.downloadFile(this.downloadSrc,this.wValue)
      this.downloadFile(this.downSrc,this.wValue)
      this.$emit('ok')
      this.handleWaterCancel()
    },
    downloadFile(href, title) {
      // 创建元素
      var link = document.createElement('a')
      link.href = href
      // 模拟点击操作，触发下载
      link.style.display = 'none'
      link.setAttribute('download', title)
      document.body.appendChild(link)
      link.click()
      // 清理资源
      document.body.removeChild(link)
      URL.revokeObjectURL(href)
    },
  },
}
</script>
<style lang="less" scoped>
.watermark {
  display: flex;
  align-items: center;
}
.wleft {
  width: 50%;
  .wcontent {
    display: flex;
    align-items: center;
    margin: 0 0 10px 10px;
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 20%;
    }
  }
}
.wright {
  width: 240px;
  background: #ddd;
  border: 1px solid #ccc;
  margin-left: 60px;
  height: 300px;
  padding: 10px;
}
</style>
